package com.xiaoyi.library.controller;

import com.xiaoyi.library.pojo.Book;
import com.xiaoyi.library.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
public class BookController {
    private final BookService bookService;

    @Autowired
    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    @RequestMapping("/loadingbook")
    public List<Book> query() {
        List<Book> list = bookService.find();
        return list;
    }

    @GetMapping("/search")
    public List<Book> search(String bookName) {
        List<Book> list = bookService.findByName(bookName);
        return list;
    }

    @DeleteMapping("/delete")
    public boolean delete(int bookId) {
        try {
            // 调用 BookService 的 deleteById 方法进行删除操作
            return bookService.deleteById(bookId);
        } catch (Exception e) {
            e.printStackTrace();
            return false;  // 删除失败，返回 false
        }
    }

    @PostMapping("/add")
    public boolean addBook(@RequestBody Book book) {
        try {
            // 调用 BookService 的 insert 方法进行插入操作
            return bookService.insert(book);
        } catch (Exception e) {
            e.printStackTrace();
            return false;  // 插入失败，返回 false
        }
    }

    @PutMapping("/edit")
    public boolean updateBook(@RequestBody Book book) {
        try {
            // 调用 BookService 的 update 方法进行更新操作
            return bookService.update(book);
        } catch (Exception e) {
            e.printStackTrace();
            return false;  // 更新失败，返回 false
        }
    }
}
